﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using HanGu.Services.Interface;
using HanGu.Entity;
using HanGu.Common;
using System.IO;
using System.Text;

namespace HanGu.CRM.Controllers
{
    public class FileManageController : AdminBaseController
    {
        private static readonly IFileManage serviceFile = ServiceFactory.GetService<IFileManage>();
        const string UPLOADFILEJSON = "\"err\":\"{0}\",\"msg\":\"{1}\"";
        public ActionResult UpLoad(string guid)
        {
            FileManage model = new FileManage();
            if (!string.IsNullOrEmpty(guid))
            {
                model = serviceFile.GetByID(guid);
            }
            return View("~/Views/Admin/FileManage/UpLoad.cshtml", model);
        }

        [HttpPost]
        public ActionResult UpLoad(FormCollection collection)
        {
            FileManage model = new FileManage();
            //if (!string.IsNullOrEmpty(guid))
            //{
            //    model = serviceFile.GetByID(guid);
            //}
            return View("~/Views/Admin/FileManage/UpLoad.cshtml", model);
        }
        [HttpPost]
        public string SaveFiles(FormCollection collection)
        {
            string guid = Request["guid"];
            string classType = Request["ClassType"];
            string groupName = Request["GroupName"];
            foreach (string fileName in Request.Files)
            {
                using (UploadFileManage uploadFile = new UploadFileManage(Request.Files[fileName]))
                {
                    uploadFile.IsResetSourceName = true;
                    uploadFile.ClassType = classType;
                    uploadFile.Save();
                    if (!uploadFile.Error)
                    {
                        FileManage fileManage = new FileManage();
                        fileManage = fileManage ?? new FileManage();
                        fileManage.FileType = Request.Files[0].ContentType;
                        fileManage.IsUse = false;
                        fileManage.GroupName = groupName;
                        fileManage.Uploader = CurentUser.UserName;
                        fileManage.UploadTime = DateTime.Now;
                        fileManage.GUID = guid;
                        fileManage.FilePath = uploadFile.FileInfo["filepath"];
                        bool tag = serviceFile.Add(fileManage);
                        if (tag)
                        {
                            ajaxStr = string.Format(ajaxStr, 200, ResourceManager.SaveSuccess, navTabId, "", "");
                        }
                        else
                        { ajaxStr = string.Format(ajaxStr, 300, ResourceManager.SaveFail, navTabId, "", ""); }
                    }
                    else
                    {
                        ajaxStr = string.Format(ajaxStr, 300, ResourceManager.SaveFail, navTabId, "", "");
                    }
                }
            }
            return "{" + ajaxStr + "}";
        }



        [HttpPost]
        public string SaveFile(FormCollection collection)
        {
            if (Request.Files.Count > 0 && Request.Files[0].ContentLength > 0)
            {

                //foreach (System.Web.HttpPostedFileWrapper file in Request.Files)
                {
                    using (UploadFileManage uploadFile = new UploadFileManage(Request.Files[0]))
                    {
                        uploadFile.ClassType = Request["ClassType"];
                        uploadFile.Save();
                        if (!uploadFile.Error)
                        {
                            string guid = Request["guid"];
                            FileManage fileManage = serviceFile.GetByID(guid);
                            fileManage = fileManage ?? new FileManage();
                            fileManage.FileType = Request.Files[0].ContentType;
                            fileManage.IsUse = false;
                            fileManage.GroupName = Request["GroupName"];
                            fileManage.Uploader = CurentUser.UserName;
                            fileManage.UploadTime = DateTime.Now;

                            if (!string.IsNullOrEmpty(fileManage.GUID))
                            {
                                uploadFile.DeleteFile(fileManage.FilePath);//先删除旧图片
                                fileManage.FilePath = uploadFile.FileInfo["filepath"];
                                serviceFile.Update(fileManage);
                            }
                            else
                            {
                                guid = string.IsNullOrEmpty(guid) ? Helper.GetGuid : guid;
                                fileManage.GUID = guid;
                                fileManage.FilePath = uploadFile.FileInfo["filepath"];
                                serviceFile.Add(fileManage);
                            }
                            ajaxStr = string.Format(UPLOADFILEJSON, null, fileManage.FilePath.Replace("\\", "\\\\"));
                        }
                        else
                        {
                            ajaxStr = string.Format(uploadFile.Message, null, null);
                        }

                    }

                }
            }
            return "{" + ajaxStr + "}";
        }

        public void GetFileByID(string id)
        {
            FileManage file = serviceFile.GetByID(id);
            if (file != null)
            {
                Response.ContentType = file.FileType;
                Response.WriteFile(file.FilePath);
            }
        }

        public void DeleteExecute(string id)
        {
            List<FileManage> groupFiles = serviceFile.GetByGroupName(id);
            if (groupFiles != null)
            {
                foreach (var item in groupFiles)//删除文件
                {
                    try
                    {
                        using (UploadFileManage uploadFile = new UploadFileManage())
                        {
                            uploadFile.DeleteFile(item.FilePath);
                        }
                    }
                    catch
                    { }
                }

                serviceFile.DeleteByGroupName(id);

            }
        }
        public string DeleteByGroupName(string id)
        {
            ajaxStr = string.Format(ajaxStr, 300, ResourceManager.DeleteFail, navTabId, "", "");
            if (!string.IsNullOrEmpty(id))
            {
                try
                {
                    this.DeleteExecute(id);
                    ajaxStr = string.Format(ajaxStr, 200, ResourceManager.DeleteSuccess, navTabId, "", "");
                }
                catch (Exception ex)
                {
                    base.ExceptionHand(ex);
                }
            }
            return "{" + ajaxStr + "}";
        }
        public void GetFileByPath(string id)
        {
            string path = id;
            string fullpath = Server.MapPath(path);
            if (System.IO.File.Exists(fullpath))
            {
                FileInfo file = new FileInfo(fullpath);
                Response.Clear();//清除所有缓存区的内容  
                Response.Charset = "GB2312";//定义输出字符集
                Response.ContentEncoding = Encoding.Default;//输出内容的编码为默认编码 
                Response.AddHeader("Content-Disposition", "attachment;filename=" + file.Name);//添加头信息。为“文件下载/另存为”指定默认文件名称    
                Response.AddHeader("Content-Length", file.Length.ToString());//添加头文件，指定文件的大小，让浏览器显示文件下载的速度   
                Response.WriteFile(file.FullName);// 把文件流发送到客户端    
                Response.End();//将当前所有缓冲区的输出内容发送到客户端，并停止页面的执行
            }
        }
        //
        // GET: /FileManage/

        public ActionResult Index(string id)
        {
            var fileManage = serviceFileManage.GetByGuid(id);
            return View(fileManage);
        }

        //
        // GET: /FileManage/Details/5

        public ActionResult Details(int id)
        {
            return View();
        }

        //
        // GET: /FileManage/Create

        public ActionResult Create()
        {
            return View();
        }

        //
        // POST: /FileManage/Create

        [HttpPost]
        public ActionResult Create(FormCollection collection)
        {
            try
            {
                // TODO: Add insert logic here

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

        //
        // GET: /FileManage/Edit/5

        public ActionResult Edit(int id)
        {
            return View();
        }

        //
        // POST: /FileManage/Edit/5

        [HttpPost]
        public ActionResult Edit(int id, FormCollection collection)
        {
            try
            {
                // TODO: Add update logic here

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

        //
        // GET: /FileManage/Delete/5

        


        //
        // POST: /FileManage/Delete/5

        [HttpPost]
        public string Delete(int id)
        {
            try
            {
                try
                {
                    var model = serviceFileManage.GetByID(id);
                    using (UploadFileManage uploadFile = new UploadFileManage())
                    {
                        uploadFile.DeleteFile(model.FilePath);
                    }
                }
                catch { }
                serviceFileManage.DeleteByID(id);
                ajaxStr = string.Format(ajaxStr, 200, ResourceManager.DeleteSuccess, navTabId, "", "");
            }
            catch (Exception ex)
            {
                ExceptionHand(ex);
                ajaxStr = string.Format(ajaxStr, 300, ResourceManager.DeleteFail, navTabId, "", "");
            }

            return "{" + ajaxStr + "}";

        }
    }
}
